// eslint-disable-next-line no-unused-vars
import { getInfo, loginAuthorization, logout } from '@/api/user'
import {
  getToken,
  removeCookies,
  removeToken,
  setCookies,
  setToken
} from '@/utils/auth'
import md5 from 'js-md5'
import { resetRouter } from '../../router'

const state = {
  token: getToken(),
  roles: []
}
const defaultRoles = ['admin']

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginAuthorization({
        username,
        password: md5(password),
        grant_type: 'password',
        scope: 'read write'
      })
        .then(res => {
          const { access_token, expires_in, refresh_token } = res
          commit('SET_TOKEN', access_token)
          setToken(access_token, {
            expires: new Date(new Date().getTime() + (expires_in - 10) * 1000)
          })
          if (refresh_token) {
            // 刷新token存在时需要保存刷新token
            setCookies('refresh_token', refresh_token, { expires: 30 })
          }
          resolve(access_token)
        })
        .catch(error => {
          console.log('发生错误！', error)
          reject(error)
        })
    })
  },

  // 注销
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = {
        accessToken: getToken()
      }
      logout(data)
        .then(res => {
          removeToken() // 优先清除token
          removeCookies('refresh_token')
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 优先清除token
      resolve()
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(res => {
          if (res.data && res.data.roles === undefined) {
            res.data.roles = defaultRoles
          }
          commit('SET_ROLES', res.data.roles)
          resolve(res.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
